__version__ = "0.0.1b"

import argparse


def _compress(o) -> str:
    if isinstance(o, list):
        return _list_compress(o)
    elif isinstance(o, dict):
        return _dict_compress(o)
    elif isinstance(o, str):
        return '"%s"' % o
    else:
        return str(o)


def _dict_compress(d: dict) -> str:
    if d is None or len(d) == 0:
        return "{}"
    ret = []
    for k, v in d.items():
        k_s = _compress(k)
        v_s = _compress(v)
        ret.append("%s:%s" % (k_s, v_s))
    return "{%s}" % ",".join(ret)


def _list_compress(l: list) -> str:
    if l is None or len(l) == 0:
        return "[]"
    ret = []
    for v in l:
        v_s = _compress(v)
        ret.append(v_s)
    return "[%s]" % ",".join(ret)


def json_compress(func):
    """用于将dict格式的数据转为str时，将空格换行等去掉"""
    def wrapper(*args, **kwargs):
        return _compress(func(*args, **kwargs))
    return wrapper


# this is a decorator
def json_ret_wrapper(func):
    def wrapper(*args, **kwargs):
        try:
            ret = func(*args, **kwargs)
        except Exception as e:
            return {
                'status': 400,
                'err_msg': repr(e).replace('"', "'")
            }
        return {
            'status': 200,
            'data': ret
        }

    return wrapper


class ArgsParser:
    def __init__(self, description):
        parser = argparse.ArgumentParser(description=description)

        parser.add_argument(
            '-v'
            '--version',
            action='store_true',
            help='Print version then exit.',
            dest='version'
        )

        parser.add_argument(
            '-f',
            '--find-hosts',
            default=None,
            type=str,
            help='find all hosts alive in the subnet specified.',
            dest='find_hosts'
        )

        parser.add_argument(
            '-F',
            '--find-info',
            default=None,
            type=str,
            help='find all info of hosts alive in the subnet specified.',
            dest='find_info'
        )

        parser.add_argument(
            '-a',
            '--args',
            default=None,
            type=str,
            help='specify the user-defined args.',
            dest='args'
        )

        parser.add_argument(
            '-p',
            '--ports',
            default=None,
            type=str,
            help='specify the ports scanned.',
            dest='ports'
        )

        self.__parser = parser

    def parse_arguments(self, args=None):
        return self.__parser.parse_known_args(args)
